package com.hermit.qmst.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Environment;
import android.os.IBinder;

import com.hermit.qmst.R;


public class MediaPlayService extends Service {

    private MediaPlayer mediaPlayer;

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {

        super.onCreate();

        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        //audioManager.setMode(AudioManager.MODE_IN_CALL);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        play();

        return super.onStartCommand(intent, flags, startId);

    }

    private void play() {
        String filePath = Environment.getExternalStorageDirectory() + "/ring2.amr";
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(filePath);
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (Exception e) {
            mediaPlayer = MediaPlayer.create(MediaPlayService.this, R.raw.ring2);
            mediaPlayer.start();
        }
        //mediaPlayer.reset();

        //mediaPlayer.prepare();

        mediaPlayer.setVolume((float) 0.5, (float) 0.5);

        mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                mediaPlayer.release();
            }
        });
        mediaPlayer.setOnErrorListener(new OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                mediaPlayer.release();

                return false;
            }
        });
    }

    @Override
    public void onDestroy() {

        if (mediaPlayer != null) {

            mediaPlayer.release();
            mediaPlayer = null;

        }
        super.onDestroy();
    }


}
